<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户id" prop="uid">
        <el-input
          v-model="queryParams.uid"
          placeholder="请输入用户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户组id" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="请选择用户组id" clearable size="small">
          <el-option
            v-for="dict in groupIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省" clearable size="small">
          <el-option
            v-for="dict in provinceOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择城市" clearable size="small">
          <el-option
            v-for="dict in cityOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开发平台id" prop="openid">
        <el-input
          v-model="queryParams.openid"
          placeholder="请输入开发平台id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="介绍" prop="intro">
        <el-input
          v-model="queryParams.intro"
          placeholder="请输入介绍"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="积分" prop="integral">
        <el-input
          v-model="queryParams.integral"
          placeholder="请输入积分"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="账号类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
    <el-form-item label="创建时间">
        <el-date-picker
            v-model="daterangeCreateTime"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
    </el-form-item>
        <el-form-item label="删除时间">
        <el-date-picker
            v-model="daterangeDeleteTime"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
    </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lngx:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lngx:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lngx:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lngx:user:export']"
        >导出</el-button>
      </el-col>
        <el-col :span="1.5">
            <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['lngx:user:importData']"
            >导入</el-button>
        </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id" align="center" prop="uid" />
      <el-table-column label="用户名" align="center" prop="username" width="120" />
      <!-- <el-table-column label="密码" align="center" prop="password" /> -->
      <el-table-column label="昵称" align="center" prop="nickname" width="120" />
      <el-table-column label="用户组id" align="center" prop="groupId" :formatter="groupIdFormat" />
      <el-table-column label="头像" align="center" prop="avatar" >
      <template slot-scope="scope">
          <div id="">
            <el-image style="width: 100px; height: 50px" :src="scope.row.avatar" fit="cover"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="省" align="center" prop="province" :formatter="provinceFormat" />
      <el-table-column label="城市" align="center" prop="city" :formatter="cityFormat" />
      <el-table-column label="开发平台id" align="center" prop="openid"  width="200"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="介绍" align="center" prop="intro" width="250" />
      <el-table-column label="积分" align="center" prop="integral" />
      <el-table-column label="websocketId" align="center" prop="fd" />
      <el-table-column label="上次登陆IP" align="center" prop="lastLoginIp" />
      <el-table-column label="用户标签" align="center" prop="tagStr"  >
      <template slot-scope="scope">
          <div id="">
            <!-- <el-image style="width: 100px; height: 50px" :src="scope.row.coverImage" fit="cover"></el-image> -->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="账号类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除时间" align="center" prop="deleteTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deleteTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户wssip:fd" align="center" prop="wss" />
      <el-table-column label="加密值" align="center" prop="secret" />
      <el-table-column label="开放平台id" align="center" prop="unionid"  width="200"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lngx:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lngx:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="用户组id" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择用户组id">
            <el-option
              v-for="dict in groupIdOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <imageUpload v-model="form.avatar"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select v-model="form.province" placeholder="请选择省">
            <el-option
              v-for="dict in provinceOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="form.city" placeholder="请选择城市">
            <el-option
              v-for="dict in cityOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开发平台id" prop="openid">
          <el-input v-model="form.openid" placeholder="请输入开发平台id" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="intro">
          <el-input v-model="form.intro" placeholder="请输入介绍" />
        </el-form-item>
        <el-form-item label="积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="上次登陆IP" prop="lastLoginIp">
          <el-input v-model="form.lastLoginIp" placeholder="请输入上次登陆IP" />
        </el-form-item>
        <el-form-item label="用户标签" prop="tagStr">
          <el-input v-model="form.tagStr" placeholder="请输入用户标签" />
        </el-form-item>
        <el-form-item label="0为普通用户，1为官方账号" prop="type">
          <el-select v-model="form.type" placeholder="请选择0为普通用户，1为官方账号">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加密值" prop="secret">
          <el-input v-model="form.secret" placeholder="请输入加密值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
      <!-- 导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="upload.headers"
                  :action="upload.url + '?updateSupport=' + upload.updateSupport"
                  :disabled="upload.isUploading"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :auto-upload="false"
                  drag
          >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip text-center" slot="tip">
                  <div class="el-upload__tip" slot="tip">
                      <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
              </div>
          </el-upload>
          <el-progress :text-inside="true" :stroke-width="24" :percentage="uploadStatus" status="success"></el-progress>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/lngx/user";
import { getToken } from "@/utils/auth";

export default {
  name: "User",
  data() {
    return {
        uploadStatus:0,
        // 导入参数
        upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/lngx/user/importData"
        },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户组id字典
      groupIdOptions: [],
      // 省字典
      provinceOptions: [],
      // 城市字典
      cityOptions: [],
      // 状态字典
      statusOptions: [],
      // 0为普通用户，1为官方账号字典
      typeOptions: [],
      // 创建时间时间范围
    daterangeCreateTime: [],
      // 删除时间时间范围
    daterangeDeleteTime: [],
  // 查询参数
    queryParams: {
        pageNum: 1,
        pageSize: 10,
    uid: null,    username: null,    password: null,    nickname: null,    groupId: null,    gender: null,    province: null,    city: null,    openid: null,    status: null,    intro: null,    integral: null,    fd: null,    lastLoginIp: null,    tagStr: null,    type: null,    beginCreateTime : null,
    endCreateTime :null,
    beginDeleteTime : null,
    endDeleteTime :null,
    wss: null,    secret: null,    unionid: null      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        groupId: [
          { required: true, message: "用户组id不能为空", trigger: "change" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("user_group").then(response => {
      this.groupIdOptions = response.data;
    });
    this.getDicts("province_code").then(response => {
      this.provinceOptions = response.data;
    });
    this.getDicts("city_code").then(response => {
      this.cityOptions = response.data;
    });
    this.getDicts("user_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("user_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
      getQueryParams(){
            this.queryParams.beginCreateTime =null
            this.queryParams.endCreateTime=null
            if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
                this.queryParams.beginCreateTime = this.daterangeCreateTime[0];
                this.queryParams.endCreateTime = this.daterangeCreateTime[1];
            }
            this.queryParams.beginDeleteTime =null
            this.queryParams.endDeleteTime=null
            if (null != this.daterangeDeleteTime && '' != this.daterangeDeleteTime) {
                this.queryParams.beginDeleteTime = this.daterangeDeleteTime[0];
                this.queryParams.endDeleteTime = this.daterangeDeleteTime[1];
            }
            return this.queryParams;
      },
    /** 查询用户列表 */
    getList() {
      this.loading = true;

          listUser(this.getQueryParams()).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
    },
    // 用户组id字典翻译
    groupIdFormat(row, column) {
      return this.selectDictLabel(this.groupIdOptions, row.groupId);
    },
    // 省字典翻译
    provinceFormat(row, column) {
      return this.selectDictLabel(this.provinceOptions, row.province);
    },
    // 城市字典翻译
    cityFormat(row, column) {
      return this.selectDictLabel(this.cityOptions, row.city);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 0为普通用户，1为官方账号字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
        username: null,
        password: null,
        nickname: null,
        groupId: null,
        avatar: null,
        gender: null,
        province: null,
        city: null,
        openid: null,
        status: null,
        intro: null,
        integral: null,
        fd: null,
        lastLoginIp: null,
        updateTime: null,
        tagStr: null,
        type: null,
        createTime: null,
        deleteTime: null,
        wss: null,
        secret: null,
        unionid: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeDeleteTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.uid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const uid = row.uid || this.ids
      getUser(uid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.uid != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const uids = row.uid || this.ids;
      this.$confirm('是否确认删除用户编号为"' + uids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(uids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
      /** 导出按钮操作 */
      handleExport() {
          this.download('lngx/user/export', {
              ...this.getQueryParams()
          }, `用户_user.xlsx`)
      },
      handleImport() {
          this.upload.title = "用户导入";
          this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
          this.download('lngx/user/export', {
              pageNum: 1,
              pageSize: 10
          }, `用户.xlsx`)
      },
      getUploadStatus(){
          this.$store.commit("SET_HAS_UPDATE_STATUS",true)

      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
      },
      // 提交上传文件
      submitFileForm() {
          this.getUploadStatus()
          this.$refs.upload.submit();
      }
  }
};
</script>
